package dffconnector.services {

	import dffconnector.constants.COMMANDS;
	import dffconnector.constants.SERVICES;
	import dffconnector.core.DrupalConnector;
	import dffconnector.utils.string.objectToString;
		
	
	public class DAS_file extends DrupalConnector {
	
		public var FILES	:Array;
		public var FILES_IN_NODE :Array;
		private var CALLBACK	:Function;
		private var COMMAND	:String;
		private var BLOCKNAME	:String;

		
	// CONSTRUCTOR
		public function DAS_file(){
			super();
			init();
		}


		private function init():void{
			FILES		= new Array();
			FILES_IN_NODE	= new Array();
		}


		public function connect(_gatewayUrl:String = '', apiKey:String = ''):Boolean{
			return _connect(_gatewayUrl,apiKey, SERVICES.FILE);
		}

		
	// FILE MANIPULATION METHODS 
		public function file_get(callback:Function, faultback:Function, fid:uint , reload:Boolean = false):Boolean {
			
			CALLBACK	=	callback;
			COMMAND		=	COMMANDS.FILE_GET;
			BLOCKNAME	=	"file_" + String(fid);
			
			if (FILES[BLOCKNAME] && FILES[BLOCKNAME] is Object && !reload) {
				log('DrupalSite: info: Using cache data for file BLOCKNAME::' + BLOCKNAME);
				CALLBACK(FILES[BLOCKNAME]);
				return true;
			}
			return startBlocking(onData, faultback, BLOCKNAME, COMMAND, fid);
		}


		public function file_node_get(callback:Function, faultback:Function, nid:uint , reload:Boolean = false):Boolean {
			
			CALLBACK	=	callback;
			COMMAND		=	COMMANDS.FILE_NODE_GET;
			BLOCKNAME	=	"node_" + String(nid);
			
			if (FILES_IN_NODE[BLOCKNAME] && FILES_IN_NODE[BLOCKNAME] is Object && !reload) {
				log('DrupalSite: info: Using cache data for node BLOCKNAME::' + BLOCKNAME);
				CALLBACK(FILES_IN_NODE[BLOCKNAME]);
				return true;
			}
			return startBlocking(onData, faultback, BLOCKNAME, COMMAND, nid);
		}

		
	//ONDATA
		private function onData(result:Object):void {
			//dispatchEvent(new DrupalEvents(DrupalEvents.DRUPAL_DATA));
			switch (COMMAND){
				case COMMANDS.FILE_GET:{
					exec_file_get(result);
					break;
				}
				case COMMANDS.FILE_NODE_GET:{
					exec_file_node_get(result);
					break;
				}
				default:break;
			}
		}

	
	// ONDATA 	
		private function exec_file_get(result:Object):void{
			if (result){
				FILES[BLOCKNAME] = result;
				log('cached data for file ' + BLOCKNAME);
				CALLBACK(result);
			}else {
				log('bad formatted file: '+ result + BLOCKNAME, "error");
			}
			super.stopBlocking();
		}
		
		private function exec_file_node_get(result:Object):void{
			if (result && result is Array){
				FILES_IN_NODE[BLOCKNAME]= new Array();
				for (var i:* in result){
					if (result[i].filename is String){
						FILES_IN_NODE[BLOCKNAME].push(result[i]);
					}
				}
				log(result + 'cached data files for ' + BLOCKNAME);
				CALLBACK(FILES_IN_NODE[BLOCKNAME]);
			}else {
				log('bad formatted result: '+ result + BLOCKNAME, "error");
			}
			super.stopBlocking();
		}
	}
//EOF
}


